//
//  NSDecimalNumber+HECalculate.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/10/28.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "NSDecimalNumber+HECalculate.h"

@implementation NSDecimalNumber (HECalculate)


+ (NSString *)rounding:(NSString *)number afterPoint:(NSInteger)position
{
    if (number == nil) {
        number = @"0";
    }
    
    NSDecimalNumberHandler *handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode: NSRoundPlain scale: position raiseOnExactness: NO raiseOnOverflow: NO raiseOnUnderflow:NO raiseOnDivideByZero: NO];
    
    NSDecimalNumber *stringDecimal = [[NSDecimalNumber alloc] initWithString:number];
    
    NSDecimalNumber *resultNumber = [stringDecimal decimalNumberByRoundingAccordingToBehavior:handler];
    
    NSString *precision = [NSString stringWithFormat:@"%%.%ldf",position];
    
    return [NSString stringWithFormat:precision,resultNumber.doubleValue];
}

- (NSString *)afterPoint:(NSInteger)position {
    if (self == nil) {
        return @"0";
    }
    NSDecimalNumberHandler *handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode: NSRoundPlain scale: position raiseOnExactness: NO raiseOnOverflow: NO raiseOnUnderflow:NO raiseOnDivideByZero: NO];
 
    NSDecimalNumber *resultNumber = [self decimalNumberByRoundingAccordingToBehavior:handler];
    
    NSString *precision = [NSString stringWithFormat:@"%%.%ldf",position];
    
    return [NSString stringWithFormat:precision,resultNumber.doubleValue];
}

- (NSString *)keepTwo {
    return [self afterPoint:2];
}

@end
